package com.umeox.ota.engine;

import android.text.TextUtils;

import com.abupdate.iot_libs.OtaAgentPolicy;
import com.abupdate.iot_libs.data.local.OtaEntity;
import com.abupdate.iot_libs.engine.DataManager;
import com.abupdate.iot_libs.engine.otaStatus.OtaStatus;
import com.abupdate.iot_libs.engine.otaStatus.OtaStatusMgr;
import com.abupdate.iot_libs.engine.policy.PolicyManager;
import com.abupdate.iot_libs.engine.security.FotaException;
import com.abupdate.iot_libs.engine.thread.NamedRunnable;
import com.abupdate.iot_libs.utils.NetUtils;
import com.abupdate.trace.Trace;
import com.umeox.ota.R;
import com.umeox.ota.data.constant.Constant;
import com.umeox.ota.data.constant.TRIGGER;
import com.umeox.ota.gloable.App;
import com.umeox.ota.service.OtaService;
import com.umeox.ota.ui.activity.MainActivity;
import com.umeox.ota.utils.ActivityCollector;
import com.umeox.ota.utils.RxTime;


/**
 * @author fighter_lee
 * @date 2018/9/3
 */
public class NetworkChangeDispatcher extends NamedRunnable {

    private static final String TAG = "NetworkChangeDispatcher";

    public NetworkChangeDispatcher() {
        super(TAG);
    }

    @Override
    protected void execute() {
        synchronized (this) {
            OtaStatusMgr otaStatusMgr = OtaStatusMgr.getInstance();
            OtaEntity mainEntity;
            try {
                mainEntity = DataManager.getInstance().getMainEntity();
            } catch (FotaException e) {
                e.printStackTrace();
                return;
            }
            PolicyManager policyManager = mainEntity.getPolicyManager();
            //是否下载失败
            if (otaStatusMgr.getCurStatus() == OtaStatus.DOWNLOAD_FAILED) {
                Trace.d(TAG, "NetworkChangeDispatcher() Download failed: " + otaStatusMgr.getCurStatus().name());

                //根据策略判断是否强制下载
                if (policyManager.isDownloadForce()) {
                    int downloadTime = ((App) App.sCx).getDB().queryDownloadTime();
                    Trace.i(TAG, "download time:" + downloadTime + " , max download time:" + Constant.MAX_DOWNLOAD_RETRY_TIME);
                    if (downloadTime > Constant.MAX_DOWNLOAD_RETRY_TIME) {
                        //超过最大重试次数
                        Trace.d(TAG, "下载超过最大重试次数");
                        return;
                    }
                    boolean canDownload = !policyManager.isRequestWifi() || NetUtils.NETWORK_WIFI.equals(NetUtils.getNetworkState(App.sCx));
                    //如果当前设备的网络为wifi，或者策略为任意网络都能下载
                    if (canDownload) {
                        OtaService.startService(OtaService.ACTION_DOWNLOAD_TASK, TRIGGER.DOWNLOAD.DOWNLOAD_AUTO.name());
                        return;
                    }
                }
            } else if (otaStatusMgr.getCurStatus() == OtaStatus.DOWNLOADING) {
                Trace.d(TAG, "Downloading occurred connect change ");
                //下载中状态发生网络切换的话需要判断网络类型
                if (!TextUtils.equals(NetUtils.getNetworkState(App.sCx), NetUtils.NETWORK_WIFI) && policyManager.isRequestWifi()) {
                    //如果不是wifi 且不是强制下载的话，暂停下载
                    OtaAgentPolicy.download().downloadCancel();
                    //取消下载后判断是否在前台显示，如果在前台显示的话就提示用户
                    if (ActivityCollector.isShowing()) {
                        RxTime.newInstance()
                                .setICondition(() -> true)
                                .enqueue(true, new RxTime.IEnqueueListener() {
                                    @Override
                                    public void onComplete() {
                                        Trace.d(TAG, "will notice user download with mobile data ");
                                        MainActivity mainActivity = ActivityCollector.getActivity(MainActivity.class);
                                        if (mainActivity != null) {
                                            mainActivity.createDownloadChooseDialog(App.sCx.getString(R.string.tips_only_wifi_download));
                                        }
                                    }

                                    @Override
                                    public void onTimeOut() {

                                    }
                                });

                    } else {
                        Trace.d(TAG, "APP is not displayed in the foreground, download will be cancel ");
                    }
                } else {
                    Trace.d(TAG, "Will do nothing  ");
                }
            }
        }
    }
}
